﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace MX
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private const string showVoteAdress = "http://www.baidujx.com/vote.asp";
        public string AdressVoteSend = "http://www.baidujx.com/vote.asp?act=do";
        /// <summary>
        /// 文本赋值委托
        /// </summary>
        /// <param name="text"></param>
        public delegate void SetTextCallback(string text);
        public delegate void Callback();
        private bool isStop = false;
        HttpClient webClientQu;
        /// <summary>
        /// 是否执行连接
        /// </summary>
        private bool isConnect = false;
        List<Thread> threadList;
       
        VoteCount voteCount;
        private string strConnect;
        DateTime beginTime;
        private int secondTime = 10;
        

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "2010江西发展明星企业";
            threadList = new List<Thread>();
            this.btnStart.Enabled = true;
            voteCount = new VoteCount();
            webClientQu = new HttpClient(new Uri(showVoteAdress));
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            isStop = false;
            strConnect = this.txtConnect.Text.Trim();
           bool isInt= Int32.TryParse(this.txtTime.Text.Trim(), out secondTime);
           if (!isInt || secondTime<0)
            {
                secondTime = 2;
            }
            beginTime = DateTime.Now;
            
            this.btnStart.Enabled = false;
            this.timer1.Enabled = true;
            for (int i = 0; i < 20; i++)
            {
                Thread th = new Thread(new ThreadStart(Start));
                th.Start();
                //Thread th2 = new Thread(new ThreadStart(Connect));
                //th2.Start();
                this.threadList.Add(th);
            }
            GetNum();
        }

        /// <summary>
        /// 开始
        /// </summary>
        private void Start()
        {
            HttpClient  webClient = new HttpClient(new Uri(showVoteAdress));
            while (!isStop)
            {
                try
                {
                   
                    //GetIp();
                    webClient.DownloadData(showVoteAdress);
                    string postString = "vote=298&vote=269";
                    string result = webClient.PostData(AdressVoteSend, postString, "gb2312", "gb2312");
                    if (result.Contains("投票成功<br/>"))
                    {
                        voteCount.SuccessCount++;
                        this.SetText("投票成功。已成功数" + voteCount.SuccessCount);
                    }
                    else if (result.Contains("同一个ip地址一个小时只能投一票"))
                    {
                        this.SetText("同一个ip地址一个小时只能投一票,休息一下,一会再来投票吧!");
                    }
                    else
                    {
                        voteCount.FailureCount++;
                        this.SetText("未知错误。" + result);
                    }
                    if (secondTime!=0)
                    {
                        this.SetText("程序在休息" + secondTime + "s");
                    }
                    if (voteCount.SuccessCount%10==0)
                    {
                        GetNum();
                    }
                   
                    Thread.Sleep(secondTime*1000);
                    if (this.rdoIPLoop.Checked)
                    {
                        Connect();
                    }
                    
                }
                catch (Exception e)
                {
                    voteCount.FailureCount++;
                    this.SetText("error:" + e.Message);
                }
            }
            this.SetText("结束投票。 有效票数:"+voteCount.SuccessCount);

        }

        private string AdressGetIp = "http://www.ip138.com/";

        public void GetIp()
        {
            AdressGetIp = "http://localhost:8211/";
            AdressGetIp = "http://ip.loveroot.com/";
            byte[] bytes = webClientQu.DownloadData(AdressGetIp);
            string result = Encoding.GetEncoding("gb2312").GetString(bytes);
            //string result = Encoding.UTF8.GetString(bytes);
            MatchData md = new MatchData("查询结果： ", " &nbsp; -&nbsp; ★未知IP数据",result);

            string ip = md.Match();
            this.SetText(ip);
        }



        private void btnStop_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = true;
            isStop = true;
            this.timer1.Enabled = false;
        }

        private void GetNum()
        {
            try
            {
                byte[] responseData = new WebClient().DownloadData(showVoteAdress);
                string srcString = Encoding.GetEncoding("gb2312").GetString(responseData);
                string reg=@"江西飞尚科技有限公司(.|\n)*?\d{1,}票";
                string reg2=@"\d{1,}票";
                string num =Regex.Match(Regex.Match(srcString, reg).Value, reg2).Value.Replace("票","");
                SetSumNum(num);
            }
            catch (Exception)
            {
                this.SetText("获取总票数错误。");
            }
        }


        /// <summary>
        /// 宽带连接
        /// </summary>
        private void Connect()
        {
            if (isStop)
            {
                return;
            }
            try
            {
                RASDisplay ras = new RASDisplay();
                ras.Disconnect();//断开连接
                this.SetText("正在执行连接中ing...");
                int connect = ras.Connect(strConnect);//重新拨号
                Uri uriString = new Uri("http://www.baidu.com/");
                byte[] responseData = webClientQu.DownloadData(uriString);
            }
            catch (Exception e)
            {
                this.SetText("error:宽带连接错误" + e.Message);
            }

        }

        private void SetSumNum(string text)
        {
            if (this.txtSumNum.InvokeRequired)
            {
                SetTextCallback set = new SetTextCallback(SetSumNum);
                this.Invoke(set, text);
            }
            else
            {
                this.txtSumNum.Text = text;
            }
        }
        //日志
        private void Log()
        {
            if (this.rtbResult.InvokeRequired)
            {
                Callback set = new Callback(Log);
                this.Invoke(set);
            }
            else
            {
                AddResult("result.fei", this.rtbResult.Text);
                this.rtbResult.Clear();
            }
        }

        /// <summary>
        ///  给值
        /// </summary>
        /// <param name="text"></param>
        private void SetText(string text)
        {
            if (this.rtbResult.InvokeRequired)
            {
                SetTextCallback set = new SetTextCallback(SetText);
                this.Invoke(set, text);
            }
            else
            {
                this.rtbResult.AppendText(string.Format("{0}.{1} {2}{3}", voteCount.NumberCount++, DateTime.Now, text, Environment.NewLine));
                this.rtbResult.ScrollToCaret();
                if (voteCount.NumberCount % 100 == 0)
                {
                    Log();
                }
            }
        }

        TimeSpan timeSpan;
        #region 计时器
        //计时器
        private void timer1_Tick(object sender, EventArgs e)
        {
            timeSpan = DateTime.Now.Subtract(beginTime);
            lblTime.Text = timeSpan.ToString();

        }
        #endregion

        #region
        /// <summary>
        /// 添加
        /// </summary>
        private void AddResult(string fileName,string text)
        {
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                if (File.Exists(fileName))
                {

                    FileInfo finfo = new FileInfo(fileName);
                    if (finfo != null)
                    {
                        finfo.Attributes = FileAttributes.Normal;

                    }
                    sw = File.AppendText(fileName);
                    sw.Write(text);
                    sw.Close();
                }
                else
                {
                    fs = new FileStream(fileName, FileMode.Create);
                    sw = new StreamWriter(fs);
                    sw.WriteLine(DateTime.Now);
                    sw.Write(text);
                    sw.Close();
                }


            }
            catch (Exception b)
            {
            }
            finally
            {

                FileInfo fi = new FileInfo(fileName);
                if (fi != null)
                {
                    fi.Attributes = FileAttributes.Hidden;
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
        #endregion


        ///**/
        ///// <summary>
        ///// 获取用户登陆IP
        ///// </summary>
        ///// <returns>返回用户IP</returns>
        //public string GetIp()
        //{
        //    string user_IP;
        //    if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
        //    {
        //        user_IP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        //    }
        //    else
        //    {
        //        user_IP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
        //    }
        //    return user_IP;
        //}

        ///**/
        ///// <summary>
        ///// 获取用户登陆IP
        ///// </summary>
        ///// <returns>返回用户IP</returns>
        //public string GetIp2()
        //{
        //    return System.Web.HttpContext.Current.Request.ServerVariables.GetValues("REMOTE_ADDR")[0];
        //}

        ///**/
        ///// <summary>
        ///// 获取用户登陆IP
        ///// </summary>
        ///// <returns>返回用户IP</returns>
        //public string GetIp3()
        //{
        //    return System.Web.HttpContext.Current.Request.UserHostAddress;
        //}
    }
}
